/*
 * @Author: yuki
 * @Date: 2025-10-25 17:42:26
 * @LastEditTime: 2025-11-06 19:55:39
 * @Description: 登陆注册管道服务
 */

import type { PipeTransform, ArgumentMetadata } from '@nestjs/common';
import { BadRequestException } from '@nestjs/common';
import { isEmpty } from 'lodash-es';

import type { RegisterDto, LoginDto } from '@/auth/dto/auth.dto';
import { handleError } from '@/pipe/common';

export class RegisterPipe implements PipeTransform {
  async transform(
    value: Partial<RegisterDto> | undefined,
    metadata: ArgumentMetadata
  ) {
    if (!value) {
      throw new BadRequestException('未提供注册信息');
    }
    // 避免空字符串
    if (isEmpty(value.username)) {
      value.username = null as unknown as undefined;
    }
    if (isEmpty(value.email)) {
      value.email = null as unknown as undefined;
    }
    // 如果用户名和邮箱都不存在
    if (!(value.username || value.email)) {
      throw new BadRequestException('必须提供用户名或邮箱');
    }
    if (value.password !== value.confirmPassword) {
      throw new BadRequestException('两次输入的密码不一致');
    }
    await handleError(metadata, value);
    return value;
  }
}

export class LoginPipe implements PipeTransform {
  async transform(
    value: Partial<LoginDto> | undefined,
    metadata: ArgumentMetadata
  ) {
    if (!value) {
      throw new BadRequestException('未提供登录信息');
    }
    await handleError(metadata, value);
    return value;
  }
}
